import {app, desktopCapturer, dialog, ipcMain, Menu, screen} from "electron";
import path from "node:path";
import {spawn} from "child_process";
import fs from "fs";
import axios from "axios";
import {array_index} from "../util/obj";


export let backendProcess;     //后台进程



export async function getAllResources (options) {
    try {
        const screens = screen.getAllDisplays();
        let screensMap = array_index(screens, 'id')
        const sources = await desktopCapturer.getSources(options);
        return sources.map((s, index) => ({
            id: s.id,
            name: s.name,
            index: index,
            scale: screensMap[s.display_id].scaleFactor,
            thumbnail: s.thumbnail.toDataURL(),
            width: screensMap[s.display_id].size.width,     // 会受到显示缩放影响,不一定是真实分辨率
            height: screensMap[s.display_id].size.height,   // 会受到显示缩放影响
            realWidth: parseInt(screensMap[s.display_id].size.width * screensMap[s.display_id].scaleFactor),     // 会受到显示缩放影响,不一定是真实分辨率
            realHeight: parseInt(screensMap[s.display_id].size.height * screensMap[s.display_id].scaleFactor),   // 会受到显示缩放影响
            label: screensMap[s.display_id].label,
            nativeOrigin: screensMap[s.display_id].nativeOrigin,
        }));
    } catch (error) {
        console.error(error);
        return []
    }
}

export function setResources(){
    // 处理屏幕源获取
    ipcMain.handle('get-sources', async (event, options) => {
        return await getAllResources(options);
    });
}


// 信息提示框
export function showInfo(message) {
    dialog.showMessageBox(global.mainWindow, {
        type: 'info',
        title: '提示',
        message: message,
        buttons: ['确定']
    });
}

// 警告框（带回调）
export async function showWarning(message) {
    const result = await dialog.showMessageBox(global.mainWindow, {
        type: 'warning',
        title: '警告',
        message: message,
        buttons: ['确定', '取消']
    });
    return result.response === 0; // 0=确定, 1=取消
}

// 错误框
export function showError(message) {
    dialog.showMessageBox(global.mainWindow, {
        type: 'error',
        title: '错误',
        message: message,
        buttons: ['确定']
    });
}


export function startBackend(){
    // 启动后端程序
    const backendExe = path.dirname(app.getAppPath()) + '/go-vpn.exe';
    console.log("正在启动启动后端程序["+ backendExe +"].........................................")
    backendProcess = spawn(backendExe, ['-env', 'prod']);

    backendProcess.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });

    backendProcess.stderr.on('data', (data) => {
        console.error(`stderr: ${data}`);
    });

    backendProcess.on('close', (code) => {
        console.log(`后端程序退出，退出码 ${code}`);
    });
}


// 拉取配置信息
export function setConfig() {
    // 直接调用api目录下的方法会导致循环引用？
    axios.request({baseURL: `http://${import.meta.env.VITE_API_URL}`, url: '/setting/list', method: 'post', params: {}}).then(res => {
        if (res.data.code !== 0) return showInfo("用户信息未配置");
        for (let i in res.data.data){
            global.appStore.set(i, res.data.data[i]);
        }
    })

    ipcMain.handle('store-get', (event, key) => {
        return global.appStore.get(key);
    });

    ipcMain.handle('store-set', (event, {key, value}) => {
        global.appStore.set(key, value);
        return true;
    });

    ipcMain.handle('store-delete', (event, key) => {
        global.appStore.delete(key);
        return true;
    });

    ipcMain.handle('store-clear', () => {
        global.appStore.clear();
        return true;
    });
}

export function appInit(){
    setConfig();

    // 通过 IPC 暴露给渲染进程
    ipcMain.handle('dialog-info', (event, message) => {
        showInfo(message);
    });

    ipcMain.handle('dialog-warning', async (event, message) => {
        return await showWarning(message);
    });

    ipcMain.handle('dialog-error', (event, message) => {
        showError(message);
    });

    // 设置日志路径
    const logsPath = path.join(path.dirname(app.getAppPath()), '/electron-log');
    app.setAppLogsPath(logsPath);
    // 确保日志目录存在
    if (!fs.existsSync(logsPath)) {
        fs.mkdirSync(logsPath);
    }
}

export function setMenu(){
    const menu = Menu.buildFromTemplate([
        {
            label: '窗口',
            submenu: [
                {click: () => global.mainWindow.webContents.send('navigate', "/"), label: '主页'},
            ]
        }
    ]);
    Menu.setApplicationMenu(menu);
}